package org.testfire.realm.control.testfire;

import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.apache.log4j.Logger;
import org.testfire.realm.control.user.UserBean;
import org.testfire.realm.model.entities.testfire.TestsetResultEntity;
import org.testfire.realm.util.MapStoreBean;

/**
 * Created by IntelliJ IDEA.
 * User: granum
 * Date: Aug 22, 2007
 * Time: 2:06:59 PM
 * <p/>
 * Request managed bean.
 */
public class TestsetResultBean
{
    // Inject the lgsrealm entity manager, as defined in the persistence.xml file.
    @PersistenceContext(unitName = "testfire")
    EntityManager em;

    @Resource
    private UserTransaction utx;

    private UserBean userBean;

    List<TestsetResultEntity> testsetResults;

    Logger log = Logger.getLogger( TestsetBean.class );

    private TestsetResultEntity testsetResult;

    private MapStoreBean mapStoreBean;

    public TestsetResultEntity getTestsetResult( Integer id )
    {
        if ( testsetResult == null )
        {
            try
            {
                testsetResult = em.find( TestsetResultEntity.class, id );
            }
            catch ( Exception e )
            {
                log.error( "Could not find / refresh testset object.", e );
            }
        }
        return testsetResult;
    }

    public List<TestsetResultEntity> getTestsetResults()
    {
        if ( this.testsetResults == null )
        {
            Integer id = (Integer)mapStoreBean.get( "testsetId" );
            Query query;
            if ( id != null )
            {
                query = em.createQuery(
                    "SELECT OBJECT(tr) FROM TestsetResultEntity tr, TestsetEntity ts where ts.id = :testsetId" );
                query.setParameter( "testsetId", id );
            }
            else
            {
                query = em.createQuery( "SELECT OBJECT(tr) FROM TestsetResultEntity tr" );
            }
            this.testsetResults = query.getResultList();
        }
        return this.testsetResults;
    }

    public UserBean getUserBean()
    {
        return userBean;
    }

    public void setUserBean( UserBean userBean )
    {
        this.userBean = userBean;
    }

    public void setMapStoreBean( MapStoreBean mapStoreBean )
    {
        this.mapStoreBean = mapStoreBean;
    }
}